from flask import Blueprint, request, jsonify
from extensions import db
from models import User, Employee
from utils import success, error, bad_request, forbidden
from utils.file_handler import FileHandler
from flask_jwt_extended import jwt_required, get_jwt_identity
import os

# 创建文件上传API蓝图
upload_api = Blueprint('upload_api', __name__, url_prefix='/api/upload')

# 上传头像
@upload_api.route('/avatar', methods=['POST'])
@jwt_required()
def upload_avatar():
    """上传用户头像"""
    try:
        # 获取当前用户
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        
        if not user:
            return error(code=401, msg='用户不存在').to_response()
        
        # 检查是否有文件上传
        if 'file' not in request.files:
            return bad_request(msg='没有选择文件').to_response()
        
        file = request.files['file']
        
        # 验证文件
        is_valid, error_msg = FileHandler.validate_image_file(file)
        if not is_valid:
            return bad_request(msg=error_msg).to_response()
        
        # 保存文件
        result = FileHandler.save_file(file, 'image')
        
        if not result['success']:
            return error(msg=result['error']).to_response()
        
        # 删除旧头像（如果存在）
        if user.avatar:
            old_avatar_path = user.avatar
            # 如果旧头像是相对路径，需要转换为绝对路径
            if not os.path.isabs(old_avatar_path):
                old_avatar_path = os.path.join(os.getcwd(), old_avatar_path)
            FileHandler.delete_file(old_avatar_path)
        
        # 更新用户头像信息
        avatar_url = FileHandler.get_file_url(result['relative_path'])
        user.avatar = avatar_url  # 存储处理后的路径
        user.updated_at = db.func.now()
        
        db.session.commit()
        
        # 返回结果
        data = {
            'avatar_url': avatar_url
        }
        
        return success(data=data, msg='头像上传成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(msg=f'头像上传失败: {str(e)}').to_response()

# 上传文档
@upload_api.route('/document', methods=['POST'])
@jwt_required()
def upload_document():
    """上传文档文件"""
    try:
        # 获取当前用户
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        
        if not user:
            return error(code=401, msg='用户不存在').to_response()
        
        # 检查是否有文件上传
        if 'file' not in request.files:
            return bad_request(msg='没有选择文件').to_response()
        
        file = request.files['file']
        
        # 验证文件
        if not file or not file.filename:
            return bad_request(msg='没有选择文件').to_response()
        
        filename = file.filename
        if not FileHandler.allowed_file(filename, 'document'):
            return bad_request(msg=f"不支持的文档格式，只支持: {', '.join(FileHandler.ALLOWED_EXTENSIONS['document'])}").to_response()
        
        # 检查文件大小
        file.seek(0, 2)
        file_size = file.tell()
        file.seek(0)
        
        if file_size > FileHandler.MAX_FILE_SIZE['document']:
            return bad_request(msg=f"文档大小超过限制 ({FileHandler.MAX_FILE_SIZE['document'] // (1024*1024)}MB)").to_response()
        
        # 保存文件
        result = FileHandler.save_file(file, 'document')
        
        if not result['success']:
            return error(msg=result['error']).to_response()
        
        # 返回结果
        data = {
            'file_url': FileHandler.get_file_url(result['relative_path'])
        }
        
        return success(data=data, msg='文档上传成功').to_response()
        
    except Exception as e:
        return error(msg=f'文档上传失败: {str(e)}').to_response()

# 删除文件
@upload_api.route('/file', methods=['DELETE'])
@jwt_required()
def delete_file():
    """删除文件"""
    try:
        # 获取当前用户
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        
        if not user:
            return error(code=401, msg='用户不存在').to_response()
        
        # 获取文件路径
        data = request.get_json()
        if not data or 'file_path' not in data:
            return bad_request(msg='请提供文件路径').to_response()
        
        file_path = data['file_path']
        
        # 检查文件是否属于当前用户（安全验证）
        # 这里可以添加更严格的权限检查
        
        # 删除文件
        success_flag = FileHandler.delete_file(file_path)
        
        if success_flag:
            return success(msg='文件删除成功').to_response()
        else:
            return error(msg='文件删除失败').to_response()
        
    except Exception as e:
        return error(msg=f'文件删除失败: {str(e)}').to_response()

# 获取文件信息
@upload_api.route('/file-info', methods=['GET'])
@jwt_required()
def get_file_info():
    """获取文件信息"""
    try:
        # 获取当前用户
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        
        if not user:
            return error(code=401, msg='用户不存在').to_response()
        
        # 获取文件路径参数
        file_path = request.args.get('file_path')
        if not file_path:
            return bad_request(msg='请提供文件路径').to_response()
        
        # 检查文件是否存在
        if not os.path.isabs(file_path):
            file_path = os.path.join(os.getcwd(), file_path)
        
        if not os.path.exists(file_path):
            return error(code=404, msg='文件不存在').to_response()
        
        # 获取文件信息
        stat = os.stat(file_path)
        
        data = {
            'filename': os.path.basename(file_path),
            'file_size': stat.st_size,
            'created_time': stat.st_ctime,
            'modified_time': stat.st_mtime,
            'file_url': FileHandler.get_file_url(file_path)
        }
        
        return success(data=data).to_response()
        
    except Exception as e:
        return error(msg=f'获取文件信息失败: {str(e)}').to_response()
